package com.applet.system.service.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.applet.system.mapper.ActionMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.applet.system.entity.Action;
import com.applet.system.service.ActionService;

import javax.annotation.Resource;

@Service
public class ActionServiceImpl implements ActionService{

    @Resource
    private ActionMapper actionMapper;

	@Resource
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public List<Action> loadActionAuth(Long userId) {
		List<Action> actions = this.actionMapper.getActionAuth(userId);
		Set<String> codes = new HashSet<>();
		Set<String> urls = new HashSet<>();
    	actions.forEach(action->{
    		codes.add(action.getCode());
    		String _url = action.getUrl();
    		String[] _urls = _url.split("\\|");
    		for (int i = 0; i < _urls.length; i++) {
    			urls.add(_urls[i]);
			}
    	});
    	final String url_key = "console:user:resource:url:" + userId;
    	final String code_key = "console:user:resource:code:" + userId;
    	this.stringRedisTemplate.delete(url_key);
    	this.stringRedisTemplate.delete(code_key);
    	if (!codes.isEmpty()) {
        	this.stringRedisTemplate.opsForList().leftPushAll(code_key, codes);
        	this.stringRedisTemplate.expire(code_key, 30, TimeUnit.MINUTES);
		}
    	if (!codes.isEmpty()) {
        	this.stringRedisTemplate.opsForList().leftPushAll(url_key, urls);
        	this.stringRedisTemplate.expire(url_key, 30, TimeUnit.MINUTES);
		}
		return actions;
	}

	@Override
	public boolean validateUrl(Long userId, String url) {
    	final String url_key = "console:user:resource:url:" + userId;
    	if (!this.stringRedisTemplate.hasKey(url_key)) {
    		this.loadActionAuth(userId);
    	}
    	List<String> urls = this.stringRedisTemplate.opsForList().range(url_key, 0, -1);
		return urls.contains(url);
	}

	@Override
	public Map<String,Boolean> validateCodes(Long userId, List<String> codes) {
    	final String code_key = "console:user:resource:code:" + userId;
    	if (!this.stringRedisTemplate.hasKey(code_key)) {
    		this.loadActionAuth(userId);
    	}
    	List<String> allCodes = this.stringRedisTemplate.opsForList().range(code_key, 0, -1);
    	Map<String, Boolean> result = new HashMap<>();
    	for (String code : codes) {
    		result.put(code, allCodes.contains(code));
		}
		return result;
	}
    

}
